<?php
/**
 * @author huwhois<huwhois@163.com>
 */
namespace app\admin\controller;

use daswork\Controller;
use app\admin\model\User;

class Login extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new User();
        session_start();
    }

    public function index()
    {
        if ($_SERVER['REQUEST_METHOD']=='POST') {
            $param = escapeString($_POST);
            // var_dump($param);
            // exit;
            $username = trim($param['username']);
            $password = trim($param['passwd']);

            if (!$username || !$password) {
                echo "<script>alert('用户名/密码/不能为空');location.href='http://meeting.ecorr.org/admin/login/index';</script>";
                return false;
            }

            $info = $this->model->getOneByUsername($username);
 
            if (!$info || md5($password) != $info['password']) {
                $this->assign('code', 0);
                $this->assign('msg', '用户名/密码不正确');
                $this->assign('url', '/admin/login/index');
                $this->assign('wait', 2);
                $this->fetch('jump.html');
                // die("<script>alert('用户名/密码不正确');location.href='http://meeting.ecorr.org/admin/login/index';</script>");
                return false;
            }
            // 记录登录时间
            $info['last_time'] = time();
            $this->model->updateById($info);
            $_SESSION['admin'] = true;
            $_SESSION['username'] = $username;
            $_SESSION['userid'] = $info['id'];
            
            $this->assign('code', 1);
            $this->assign('msg', '登录成功');
            $this->assign('url', '/admin/index/index');
            $this->assign('wait', 3);
            $this->fetch('jump.html');
        } else {
            if (isset($_SESSION["admin"]) && $_SESSION["admin"] === true) {
                echo "alert('您已登录');<script>location.href='http://meeting.ecorr.org/admin/index/index';</script>";
                // return false;
            } else {
                $this->fetch();
            }
        }
    }

    public function logout()
    {
        session_destroy();
        return $this->fetch('index.html');
    }
}